package com.weiaibenpao.demo.chislim.ui.activity.running;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.maps.AMap;
import com.amap.api.maps.AMapOptions;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.maps.model.PolylineOptions;
import com.orhanobut.logger.Logger;
import com.weiaibenpao.demo.chislim.R;
import com.weiaibenpao.demo.chislim.TwoPointLine;
import com.weiaibenpao.demo.chislim.base.BaseActivity;
import com.weiaibenpao.demo.chislim.db.preferences.RunningPreferences;
import com.weiaibenpao.demo.chislim.db.preferences.UserPreferences;
import com.weiaibenpao.demo.chislim.utils.Constant;
import com.weiaibenpao.demo.chislim.utils.PolyLinesUtils;
import com.weiaibenpao.demo.chislim.utils.SystemUtil;
import com.weiaibenpao.demo.chislim.utils.Utils;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class StartRunActivity extends BaseActivity {
    public final static int POLYLINE_OVER_SUCCESS = 1010;

    @BindView(R.id.btn_group)
    RadioGroup btnGroup;
    @BindView(R.id.mapView)
    MapView mapView;
    @BindView(R.id.text_content1)
    TextView textContent1;
    @BindView(R.id.text_content2)
    TextView textContent2;
    @BindView(R.id.map_type_layout)
    View mapLayout;
    @BindView(R.id.img_interest)
    ImageView imgInterest;
    @BindView(R.id.layout_run_color)
    View layoutRunColor;
    private int sportType;
    private int defaultType;
    private AMap map;
    private double latitude;
    private double longitude;
    private PolyLinesUtils polyLinesUtils;
    private String code;
    private int pointNum;
    private List<TwoPointLine> twoPointLines;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case POLYLINE_OVER_SUCCESS:
                    twoPointLines = (List<TwoPointLine>) msg.obj;
                    if (twoPointLines != null && twoPointLines.size() > 0) {
                        pointNum = twoPointLines.size();
                        if (runDistance > 0) {
                            drawLine();
                        }
                    }
                    break;
            }
        }
    };

    /**
     * 选择不同的城市，如果已经有跑步里程，画图
     */

    private void drawLine() {

        int currentNum = (int) (pointNum * (runDistance / districtDistance));
        for (int i = 0; i < currentNum; i++) {
            PolylineOptions options = new PolylineOptions();
            options.width(12).color(getResources().getColor(R.color.color_run)).zIndex(200);
            options.addAll(twoPointLines.get(i).getLatLngs());
            map.addPolyline(options);
        }
    }

    private float runDistance;
    private Bitmap bitmap;
    private float districtDistance;
    private byte[] bis;
    private String provinceName;

    @Override
    public int setLayoutResourceID() {
        return R.layout.activity_start_run;
    }

    public static void openActivity(Context context, int sportType, String code, float runDistance, String province, float districtDistance, byte[] bitmap, double latitude, double longitude) {
        Intent intent = new Intent(context, StartRunActivity.class);
        intent.putExtra(Constant.SPORT_TYPE, sportType);
        intent.putExtra(Constant.CITY_CODE, code);
        intent.putExtra(Constant.RUN_DISTANCE, runDistance);
        intent.putExtra(Constant.BITMAP, bitmap);
        intent.putExtra(Constant.LATITUDE, latitude);
        intent.putExtra(Constant.LONGITUDE, longitude);
        intent.putExtra(Constant.DISTRICT_DISTANCE, districtDistance);
        intent.putExtra(Constant.PROVINCE, province);
        context.startActivity(intent);
    }

    @Override
    public void init(Bundle savedInstanceState) {
        if (UserPreferences.getInstance().getIsShowWhiteListNotice()) {
            showWhiteListNotice();
            Logger.e("StartRun--init--允许弹出提示 ");
        } else {
            Logger.e("StartRun--init--不再弹出提示 ");
        }

        sportType = getIntent().getIntExtra(Constant.SPORT_TYPE, 1);

        runDistance = getIntent().getFloatExtra(Constant.RUN_DISTANCE, 0f);
        layoutRunColor.setVisibility(View.GONE);
        mapView.onCreate(savedInstanceState);
        initMap();
        defaultType = sportType;
        selectShowView();
        btnGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.btn_out_run:
                        sportType = defaultType;
                        break;
                    case R.id.btn_home_run:
                        sportType--;
                        break;

                }
                selectShowView();
            }
        });
    }

    /**
     * 判断跑步类型，显示不同的界面
     */
    private void selectShowView() {
        if (sportType == 1 || sportType == 3 || sportType == 5) {
            mapLayout.setVisibility(View.VISIBLE);
            textContent1.setVisibility(View.GONE);
            textContent2.setVisibility(View.GONE);
        }
        if (sportType == 0) {
            mapLayout.setVisibility(View.GONE);
            textContent2.setVisibility(View.VISIBLE);
        }
        if (sportType == 2 || sportType == 4) {
            mapLayout.setVisibility(View.VISIBLE);
            textContent1.setVisibility(View.VISIBLE);
            textContent2.setVisibility(View.GONE);
        }
    }

    private void initMap() {

        if (map == null) {
            map = mapView.getMap();
        }
        map.getUiSettings().setZoomGesturesEnabled(false);//禁用或启用缩放手势
        map.getUiSettings().setScrollGesturesEnabled(false);//禁用或开启平移（滑动）手势
        map.getUiSettings().setZoomControlsEnabled(false);
        map.getUiSettings().setLogoPosition(AMapOptions.LOGO_POSITION_BOTTOM_RIGHT);//设置logo位置
        latitude = getIntent().getDoubleExtra(Constant.LATITUDE, 39.906901);
        longitude = getIntent().getDoubleExtra(Constant.LONGITUDE, 116.397972);

        /**
         * 常规跑步
         */
        if (sportType == 0 || sportType == 1) {
            setMyLocationStyleIcon();
            map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude), 15f));
        }
        /**
         * 中国跑
         */
        if (sportType == 2 || sportType == 3) {
            code = getIntent().getStringExtra(Constant.CITY_CODE);
            provinceName = getIntent().getStringExtra(Constant.PROVINCE);
            map.getUiSettings().setZoomGesturesEnabled(false);//禁用或启用缩放手势
            map.getUiSettings().setScrollGesturesEnabled(false);//禁用或开启平移（滑动）手势
            layoutRunColor.setVisibility(View.VISIBLE);
            districtDistance = getIntent().getFloatExtra(Constant.DISTRICT_DISTANCE, 0);
            polyLinesUtils = new PolyLinesUtils(this, map);
            polyLinesUtils.drawLine(code, mHandler);
        }
        /**
         * 趣味跑
         */
        if (sportType == 4 || sportType == 5) {

            bis = getIntent().getByteArrayExtra(Constant.BITMAP);
            bitmap = BitmapFactory.decodeByteArray(bis, 0, bis.length);
            map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude), 15f));
            imgInterest.setVisibility(View.VISIBLE);
            if (bitmap != null)
                imgInterest.setImageBitmap(bitmap);
        }
    }

    /**
     * 自定义系统定位小蓝点
     */
    protected void setMyLocationStyleIcon() {
        MyLocationStyle myLocationStyle = new MyLocationStyle();//初始化定位蓝点样式类myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE);//连续定位、且将视角移动到地图中心点，定位点依照设备方向旋转，并且会跟随设备移动。（1秒1次定位）如果不设置myLocationType，默认也会执行此种模式。
        myLocationStyle.interval(2000); //设置连续定位模式下的定位间隔，只在连续定位模式下生效，单次定位模式下不会生效。单位为毫秒。
        map.setMyLocationStyle(myLocationStyle);//设置定位蓝点的Style
        map.setMyLocationEnabled(true);// 设置为true表示启动显示定位蓝点，false表示隐藏定位蓝点并不进行定位，默认是false。
    }

    @OnClick({R.id.img_back, R.id.btn_start_run})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_back:
                finish();
                break;
            case R.id.btn_start_run:
                startRun();
                break;
        }
    }

    private void startRun() {
        if (sportType == 1 || sportType == 3 || sportType == 5) {
            if (shouldEnableGps()) {
                return;
            }
        }
        if (sportType == 0) {
            NormalIndoorRunActivity.startSelf(this);
        } else if (sportType == 1) {
            NormalOutdoorRunActivity.startSelf(this);
        } else if (sportType == 2) {
            saveData();
            ChinaInRunActivity.openActivity(this);

        } else if (sportType == 3) {
            saveData();
            ChinaOutRunActivity.openActivity(this);

        } else if (sportType == 4) {
            InterestInRunActivity.startSelf(this, runDistance, latitude, longitude);
        } else if (sportType == 5) {
            InterestOutRunActivity.startSelf(this, runDistance, latitude, longitude);
        }
        finish();
    }

    private void saveData() {
        if (!TextUtils.isEmpty(code)) RunningPreferences.getInstance().setDistrictCode(code);
        RunningPreferences.getInstance().setRunDistance(runDistance);
        RunningPreferences.getInstance().setDistrictDistance(districtDistance);
        RunningPreferences.getInstance().setSportType(sportType);
        RunningPreferences.getInstance().setDistrict(provinceName);
        Logger.e("code===" + RunningPreferences.getInstance().getDistrictCode());

    }

    private boolean shouldEnableGps() {
        if (!Utils.isGPSEnabled(this)) {
            Utils.enableGPS(this);
            Toast.makeText(this, getString(R.string.gps_enable_notice), Toast.LENGTH_LONG).show();
            return true;
        }
        return false;
    }

    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }

    @Override
    protected void onDestroy() {
        mapView.onDestroy();
        super.onDestroy();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    private void showWhiteListNotice() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(getString(R.string.notice));
        String message;
        if (SystemUtil.getSystemModel().contains(SystemUtil.MODEL_OPPO)) {
            message = getString(R.string.oppo_white_list_notice);
        } else {
            message = getString(R.string.white_list_notice);
        }
        builder.setMessage(message);
        builder.setNegativeButton(getString(R.string.not_notify), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                UserPreferences.getInstance().setIsShowWhiteListNotice(false);
                Logger.e("StartRun--after set false " + UserPreferences.getInstance().getIsShowWhiteListNotice());
            }
        });
        builder.setPositiveButton(getString(R.string.get_it), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

            }
        });
        builder.setCancelable(true);
        AlertDialog dialog = builder.create();
        dialog.show();
        dialog.getButton(dialog.BUTTON_POSITIVE).setTextColor(getResources().getColor(R.color.themeColor));
        dialog.getButton(dialog.BUTTON_NEGATIVE).setTextColor(Color.parseColor("#666666"));
    }

}
